<?php
/**
 *   Joomdiet - components/com_joomdiet/models/diet.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
class JoomdietModelDiet extends JModel
{
    var $_diet;
    var $_data;
    var $_id; // selected id
    
    function __construct()
    {
        parent::__construct();
    }
    
    function _buildBaseQuery()
    {
        $this->_query = 'SELECT * FROM #__joomdiet_Diet';
        return $this->_query;
    }
    
    function _buildFilter($query)
    {
        $words = explode(' ', $query);
        $this->_query = ' WHERE 1=1';
        foreach ($words as $word) {
            $this->_query .= ' AND (name LIKE "%'.$word.'%"';
            $this->_query .= ' OR description LIKE "%'.$word.'%")';
        }
        return $this->_query;
    }
    
    function getData()
    {
        if (empty($this->_data)) {
            $this->_buildBaseQuery();
            $this->_buildFilter();
            $this->_db->setQuery($this->_query);
            $this->_data = $this->_db->loadObjectList();
        }
        
        return $this->_data;
    }
    
    function setId($id) 
    {
        $this->_id = $id;
        $this->_diet = null;
    }
    
    function getDiet()
    {
        if (empty($this->_diet)) {
            $query = 'SELECT * FROM #__joomdiet_Diet WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_diet = $this->_db->loadObject();
        }
        
        return $this->_diet;
    }
}
?>
